package ar.edu.itba.it.paw.web.filter;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UserFilter implements Filter{

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
		
		String url = ((HttpServletRequest)request).getRequestURL().toString();
		String suburl = url.substring(url.lastIndexOf('/')+1, url.length());
		ArrayList<String> tobeFiltered = new ArrayList<String>();
		tobeFiltered.add("editProduct"); tobeFiltered.add("editForm"); tobeFiltered.add("addProduct");
		tobeFiltered.add("categoryTransaction");
		tobeFiltered.add("editUser");
		
		HttpSession sesion = ((HttpServletRequest)request).getSession(false);
		
		if ((sesion != null && sesion.getAttribute("usuario") != null) || !tobeFiltered.contains(suburl)) {
			/*esta sentencia es para ejecutar el servlet*/
			chain.doFilter(request, response);
			return;
		}
		
		((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/bin/user/index?red=1");
	}
	
	public void destroy() {}
	
	public void init(FilterConfig arg0) throws ServletException {}
}
